package com.inno.life.domain.service.impl;

import com.inno.life.common.enums.YesOrNoEnum;
import com.inno.life.domain.convert.MessagesConverter;
import com.inno.life.domain.entity.MessagesBO;
import com.inno.life.domain.service.LifeMessagesDomainService;
import com.inno.life.infra.basic.entity.PlannerMessages;
import com.inno.life.infra.basic.service.PlannerMessagesService;
import com.inno.life.infra.entity.UserInfo;
import com.inno.life.infra.rpc.UserRpc;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class LifeMessagesDomainServiceImpl implements LifeMessagesDomainService {
    private final PlannerMessagesService plannerMessagesService;
    private final UserRpc userRpc;
    @Override
    public List<MessagesBO> queryList(MessagesBO messagesBO) {
        PlannerMessages plannerMessages = MessagesConverter.INSTANCE.convertBOToEntity(messagesBO);
        List<PlannerMessages> messagesList = this.plannerMessagesService.queryList(plannerMessages);
        List<MessagesBO> boResult = MessagesConverter.INSTANCE.convertEntityListToBoList(messagesList);
        List<Long> userIdList = boResult.stream().map(MessagesBO::getFromId).toList();
        List<UserInfo> userInfoList = userRpc.getUserInfoByIdList(userIdList);
        Map<Long, UserInfo> userInfoMap = userInfoList.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
        boResult.forEach(bo -> {
            UserInfo userInfo = userInfoMap.get(bo.getFromId());
            bo.setAvatar(userInfo.getAvatar());
        });
        return boResult;
    }

    @Override
    public void read(MessagesBO messagesBO) {
        PlannerMessages plannerMessages = MessagesConverter.INSTANCE.convertBOToEntity(messagesBO);
        plannerMessages.setId(messagesBO.getMessageId());
        plannerMessages.setIsRead(YesOrNoEnum.YES.getCode());
        this.plannerMessagesService.update(plannerMessages);
    }

    @Override
    public void readAll(MessagesBO messagesBO) {
        Long userId = messagesBO.getUserId();
        this.plannerMessagesService.readAllByUserId(userId);
    }

    @Override
    public MessagesBO unreadCount(MessagesBO messagesBO) {
        Long userId = messagesBO.getUserId();
        PlannerMessages plannerMessages = MessagesConverter.INSTANCE.convertBOToEntity(messagesBO);
        plannerMessages.setIsRead(YesOrNoEnum.NO.getCode());
        Integer count = this.plannerMessagesService.unreadCount(plannerMessages);
        messagesBO.setCount(count);
        return messagesBO;
    }
}
